package com.kele.goods.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.kele.common.model.response.Result;
import com.kele.goods.mapper.CategoryMapper;
import com.kele.model.goods.Category;
import com.kele.model.goods.dto.CategoryDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    public List<Category> findAll() {
        return categoryMapper.selectList(Wrappers.emptyWrapper());
    }

    public List<CategoryDTO> findCategoryDTO(){
        return categoryMapper.findCategoryDTO();
    }

    public List<Category> findCategoryTree(){
        List<Category> all = findAll();

        return all.stream()
                .filter((category)->category.getParentId()==0)//category 所有的
                .peek((category)->{//category 第一级
                    category.setChildren(findCategoryByParent(category,all));
                })
                .collect(Collectors.toList());
    }

    public List<Category> findCategoryByParent(Category parent,List<Category> all){
        List<Category> collect = all.stream()
                .filter(category -> {
                    //return category.getParentId() == parent.getId();
                    return category.getParentId().equals(parent.getId());//改为这样就可以了
                })//category 所有的
                .peek((category -> {//category 第2级
                    category.setChildren(findCategoryByParent(category, all));//2
                }))
                .collect(Collectors.toList());
        return collect;
    }


    public Result add(Category category) {
        categoryMapper.insert(category);
        return new Result(true,"1","新增成功");
    }

    public Result update(Category category) {
        categoryMapper.updateById(category);
        return new Result(true,"1","更新成功");
    }

    public Category findById(Long id) {
        return  categoryMapper.selectById(id);
    }

    public Result deleteById(Long id) {
        categoryMapper.deleteById(id);
        return Result.SUCCESS();
    }

    public Result deleteByIdCascade(Long id){
        categoryMapper.deleteByIdCascade(id);
        return Result.SUCCESS();
    }

    public List<Category> findByParentId(Long parentId) {
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Category::getParentId,parentId);
        return categoryMapper.selectList(queryWrapper);
    }
}
